package com.sh.fmbackend.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sh.fmbackend.common.ResultUtils;
import com.sh.fmbackend.mapper.UserMapper;
import com.sh.fmbackend.model.domain.User;
import com.sh.fmbackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Auther: sh
 * @Date: 2024/12/24 22:42
 * @Description: 缓存预热
 */
@Component
@Slf4j
public class PreHotCache {

    @Resource
    private UserMapper userPage;

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    // 重点用户 todo 动态配置
    private List<Long> mainUserList = Arrays.asList(40L);

    @Scheduled(cron = "0 0 8 * * ?")
    public void doCacheRecommendUser() {
        // 拿锁
        RLock lock = redissonClient.getLock("sh:precachejob:docache:lock");
        try {
            if (lock.tryLock(0, 30, TimeUnit.SECONDS)) {
                for (Long one : mainUserList) {
                    String key = String.format("sh:user:recommend:%s", one);
                    QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 20), objectQueryWrapper);
                    // 脱敏
                    List<User> desensitizedUserList = userPage.getRecords().stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
                    userPage.setRecords(desensitizedUserList);
                    try {
                        redisTemplate.opsForValue().set(key, userPage, 24, TimeUnit.HOURS);
                    } catch (Exception e) {
                        log.error("redis set error");
                    }
                }
                // 上面报错怎么办？ finally 兜底
//                if (lock.isHeldByCurrentThread()) {  // 是不是当前线程的锁
//                    lock.unlock();
//                }
            }
        } catch (InterruptedException e) {
            log.error("Get lock error: {}", e.getMessage());
            throw new RuntimeException(e);
        }finally {
            if (lock != null && lock.isHeldByCurrentThread()) { lock.unlock(); }
        }
    }
}

